/**
 * @project: zjport_flight
 */
package com.seedwill.common.util;

import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;

/**
 * 时间辅助
 * 
 * @datetime 2007-8-16
 * 
 */
public class DateTimeHelper {

    private static final String CLASSNAME = "DateTimeHelper:";

    private static Logger logger = Logger.getLogger(DateTimeHelper.class);

    /**
     * 日期格式 yyyy-MM-dd
     */
    private static final String DEFAULTDATEFORMAT = "yyyy-MM-dd";

    /**
     * 时间格式 HH:mm:ss
     */
    private static final String DEFAULTTIMEFORMAT = "HH:mm:ss";

    /**
     * 时间格式 HH:mm
     */
    private static final String DEFAULTSHORTTIMEFORMAT = "HH:mm";
    
    private static final String DEFAULTMIDDATEFORMAT_H2 = "yyyy-MM-dd HH";
    private static final String DEFAULTMIDDATEFORMAT_H1 = "yyyy-MM-dd H";
    /**
     * 日期时间格式 yyyy-MM-dd HH:mm
     */
    private static final String DEFAULTMIDDATEFORMAT = "yyyy-MM-dd HH:mm";

    /**
     * 日期时间格式 yyyy-MM-dd HH:mm:ss
     */
    private static final String DEFAULTLONGDATEFORMAT = "yyyy-MM-dd HH:mm:ss";

    private static final DateFormat dfDateInstance = new SimpleDateFormat(
            DEFAULTDATEFORMAT);

    private static final DateFormat dfTimeInstance = new SimpleDateFormat(
            DEFAULTTIMEFORMAT);

    private static final DateFormat dfShortTimeInstance = new SimpleDateFormat(
            DEFAULTSHORTTIMEFORMAT);
    
    private static final DateFormat dfMidDateTimeH1Instance = new SimpleDateFormat(
            DEFAULTMIDDATEFORMAT_H1);
    private static final DateFormat dfMidDateTimeH2Instance = new SimpleDateFormat(
            DEFAULTMIDDATEFORMAT_H2);

    private static final DateFormat dfMidDateTimeInstance = new SimpleDateFormat(
            DEFAULTMIDDATEFORMAT);

    private static final DateFormat dfLongDateTimeInstance = new SimpleDateFormat(
            DEFAULTLONGDATEFORMAT);

    /**
     * 取得当前的日期
     * 
     * @return
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 取得当前的时间戳
     * 
     * @return
     */
    public static Timestamp getNowTimestamp() {
        return new Timestamp(System.currentTimeMillis());
    }
    public static Calendar getNowCalendar() {
        return Calendar.getInstance();
    }
    /**
     * 取得当前日期的年,如当前年�为2007，则返回07
     * 
     * @return
     */
    public static String getShortYearStr() {
        Calendar date = Calendar.getInstance();
        return ("" + date.get(Calendar.YEAR)).substring(2);
    }

    /**
     * 取得当前日期的年,如当前年�为2007，则返回2007
     * 
     * @return
     */
    public static int getServerYear() {
        Calendar date = Calendar.getInstance();
        return date.get(Calendar.YEAR);
    }

    /**
     * 字符串转换为日期,format为字符串格式
     * 
     * @param timeStr
     *            字符串格式必须为"yyyy-MM-dd"或"yyyy-MM-dd HH:mm"或"yyyy-MM-dd HH:mm:ss"
     *            返回的日期格式为"yyyy-MM-dd 00:00:00"或"yyyy-MM-dd
     *            HH:mm:00"或"yyyy-MM-dd HH:mm:ss"
     * @param format
     *            书写格式类似"yyyy-MM-dd HH:mm:ss"
     * @return
     * @throws ParseException
     */
    public static Date parseDateTime(String timeStr, String format)
            throws ParseException {
        Date dd = null;
        if (null != timeStr) {
        	DateFormat dateFormat = new SimpleDateFormat(format);
            try {               
                dd = dateFormat.parse(timeStr);
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 字符串转换为日期
     * 
     * @param timeStr
     *            字符串格式必须为"yyyy-MM-dd HH:mm:ss"
     * @return
     * @throws ParseException
     */
    public static Date parseLongDateTime(String timeStr) throws ParseException {
        Date dd = null;
        if (null != timeStr) {
            try {
                dd = dfLongDateTimeInstance.parse(timeStr);
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 将字符串解析为时间戳
     * 
     * @param timeStr
     *            字符串格式必须为"yyyy-MM-dd HH:mm:ss"
     * @return
     * @throws ParseException
     */
    public static Timestamp parseLongTimestamp(String timeStr)
            throws ParseException {
        Timestamp dd = null;
        if (null != timeStr) {
            try {
                dd = new Timestamp(dfLongDateTimeInstance.parse(timeStr)
                        .getTime());
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 字符串转换为日期 转化后的格式为"yyyy-MM-dd HH:mm:00"
     * 
     * @param timeStr
     *            字符串格式必须为"yyyy-MM-dd HH:mm"或"yyyy-MM-dd HH:mm:ss"
     *            返回的日期格式为"yyyy-MM-dd HH:mm:00.0"
     * @return
     * @throws ParseException
     */
    public static Date parseMidDateTime(String timeStr) throws ParseException {
        Date dd = null;
        if (null != timeStr) {
            try {
                dd = dfMidDateTimeInstance.parse(timeStr);
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 将字符串解析为时间戳, 转化后的格式为"yyyy-MM-dd HH:mm:00"
     * 
     * @param timeStr
     *            字符串格式必须为"yyyy-MM-dd HH:mm"或"yyyy-MM-dd HH:mm:ss"
     *            返回的日期格式为"yyyy-MM-dd HH:mm:00.0"
     * @return
     * @throws ParseException
     */
    public static Timestamp parseMidTimestamp(String timeStr)
            throws ParseException {
        Timestamp dd = null;
        if (null != timeStr) {
            try {
                dd = new Timestamp(dfMidDateTimeInstance.parse(timeStr)
                        .getTime());
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 字符串转换为日期
     * 
     * @param timeStr
     *            字符串格式必须为"yyyy-MM-dd","yyyy-MM-dd HH:mm"或"yyyy-MM-dd HH:mm:ss"
     *            返回的日期格式为"yyyy-MM-dd 00:00:00"
     * @return
     * @throws ParseException
     */
    public static Date parseDate(String timeStr) throws ParseException {
        Date dd = null;
        if (null != timeStr) {
            try {
                dd = dfDateInstance.parse(timeStr);
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 字符串转换为时间戳
     * 
     * @param timeStr
     *            字符串格式必须为"yyyy-MM-dd HH:mm"或"yyyy-MM-dd HH:mm:ss"
     *            返回的日期格式为"yyyy-MM-dd 00:00:00"
     * @return
     * @throws ParseException
     */
    public static Timestamp parseTimestamp(String timeStr)
            throws ParseException {
        Timestamp dd = null;
        if (null != timeStr) {
            try {
                dd = new Timestamp(dfDateInstance.parse(timeStr).getTime());
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 字符串转换为本日开始时间
     * 
     * @param timeStr
     *            字符串格式必须为"yyyy-MM-dd HH:mm"或"yyyy-MM-dd HH:mm:ss"
     *            返回的日期格式为"2007-8-16 00:00:00"
     * @return
     * @throws ParseException
     */
    public static Date parseStartDateTime(String timeStr) throws ParseException {
        return DateTimeHelper.parseDate(timeStr);
    }

    /**
     * 字符串转换为本日结束时间
     * 
     * @param timeStr
     *            字符串格式必须为"yyyy-MM-dd HH:mm"或"yyyy-MM-dd HH:mm:ss"
     *            返回的日期格式为"2007-8-16 23:59:59"
     * @return
     * @throws ParseException
     */
    public static Date parseEndDateTime(String timeStr) throws ParseException {
        StringBuffer timeStrBF = new StringBuffer(timeStr.substring(0, 10));
        timeStrBF.append(" 23:59:59");
        return DateTimeHelper.parseLongDateTime(timeStrBF.toString());
    }

    /**
     * 返回当前的日期并格式化为yyyy-MM-dd
     * 
     * @return
     */
    public static String currentDateString() {
        return dfDateInstance.format(getNowDate());
    }

    /**
     * 返回当前的日期并格式化为"yyyy-MM-dd HH:mm:ss"
     * 
     * @return
     */
    public static String currentLongDateTimeString() {
        return dfLongDateTimeInstance.format(getNowDate());
    }

    /**
     * 解析小时分秒
     * 
     * @param timeStr
     *            字符串格式必须为"HH:mm:ss" 转换后的日期的年月日为1970-01-01 时间为hh:mm:ss
     * @return
     * @throws ParseException
     */
    public static Date parseTime(String timeStr) throws ParseException {
        Date dd = null;
        if (null != timeStr) {
            try {
                dd = dfTimeInstance.parse(timeStr);
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 解析小时分秒
     * 
     * @param timeStr
     *            字符串格式必须为"HH:mm:ss" 转换后的时间戳的年月日为1970-01-01 时间为hh:mm:ss
     * @return
     * @throws ParseException
     */
    public static Timestamp parseTimestampTime(String timeStr)
            throws ParseException {
        Timestamp dd = null;
        if (null != timeStr) {
            try {
                dd = new Timestamp(dfTimeInstance.parse(timeStr).getTime());
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 解析小时分
     * 
     * @param timeStr
     *            字符串格式必须为"HH:mm"或"HH:mm:ss" 转换后的日期的年月日为1970-01-01 时间为hh:mm:00
     * @return
     * @throws ParseException
     */
    public static Date parseShortDateTime(String timeStr) throws ParseException {
        Date dd = null;
        if (null != timeStr) {
            try {
                dd = dfShortTimeInstance.parse(timeStr);
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 解析小时分
     * 
     * @param timeStr
     *            字符串格式必须为"HH:mm"或"HH:mm:ss" 转换后的时间戳的年月日为1970-01-01 时间为hh:mm:00
     * @return
     * @throws ParseException
     */
    public static Time parseShortTime(String timeStr) throws ParseException {
        // logger.debug(" enter parseShortTime: " + timeStr);
        Time dd = null;
        if (null != timeStr) {
            try {
                dd = new Time(dfShortTimeInstance.parse(timeStr).getTime());
            } catch (ParseException e) {
                throw e;
            }
        }
        // logger.debug(" enter parseShortTime: " + dd.toString());
        return dd;
    }

    /**
     * 格式化为HH:mm:ss
     * 
     * @param date
     * @return
     */
    public static String formatTime(Date date) {
        String dd = null;
        if (null != date) {
            dd = dfTimeInstance.format(date);
        }
        return dd;
    }

    /**
     * 格式化为HH:mm:ss
     * 
     * @param date
     * @return
     */
    public static String formatTime(Calendar date) {
        String dd = null;
        if (null != date) {
             dd = dfTimeInstance.format(date);
        }
        return dd;
    }

    /**
     * 格式化指定时间为HH:mm
     * 
     * @param date
     * @return
     */
    public static String formatShortTime(Date date) {
        String dd = null;
        if (null != date) {
              dd = dfShortTimeInstance.format(date);
        }
        return dd;
    }

    /**
     * 格式化指定时间为HH:mm
     * 
     * @param date
     * @return
     */
    public static String formatShortTime(Calendar date) {
        String dd = null;
        if (null != date) {
             dd = dfShortTimeInstance.format(date.getTime());
        }
        return dd;
    }

    /**
     * 格式化指定日期为yyyy-MM-dd
     * 
     * @param date
     * @return
     */
    public static String formatDate(Date date) {
        String dd = null;
        if (null != date) {
            dd = dfDateInstance.format(date);
        }
        return dd;
    }

    /**
     * 格式化指定日期为yyyy-MM-dd
     * 
     * @param date
     * @return
     */
    public static String formatDate(Calendar date) {
        String dd = null;
        if (null != date) {
            dd = dfDateInstance.format(date.getTime());
        }
        return dd;
    }

    /**
     * 格式化指定日期为yyyy-MM-dd HH:mm
     * 
     * @param date
     * @return
     */
    public static String formatMidDate(Date date) {
        String dd = null;
        if (null != date) {
            dd = dfMidDateTimeInstance.format(date);
        }
        return dd;
    }

    /**
     * 格式化指定日期为yyyy-MM-dd HH:mm
     * 
     * @param date
     * @return
     */
    public static String formatMidDate(Calendar date) {
        String dd = null;
        if (null != date) {
            dd = dfMidDateTimeInstance.format(date.getTime());
        }
        return dd;
    }
    
    public static String formatLongDateVal(Long date) {
        String dd = null;
        if (null != date) {
        	//Calendar cal = Calendar.getInstance().setTimeInMillis(date);
            dd = dfLongDateTimeInstance.format(new Date(date));
        }
        return dd;
    }

    /**
     * 格式化指定日期为yyyy-MM-dd HH:mm:ss
     * 
     * @param date
     * @return
     */
    public static String formatLongDate(Date date) {
        String dd = null;
        if (null != date) {
            dd = dfLongDateTimeInstance.format(date);
        }
        return dd;
    }

    /**
     * 格式化指定日期为yyyy-MM-dd HH:mm:ss
     * 
     * @param date
     * @return
     */
    public static String formatLongDate(Calendar date) {
        String dd = null;
        if (null != date) {
           dd = dfLongDateTimeInstance.format(date.getTime());
        }
        return dd;
    }

    /**
     * 取得两个日期的天数之差
     * 
     * @param dStart
     * @param dEnd
     * @return
     */
    public static int getTimeSpanDay(Date dStart, Date dEnd) {
        long diff = dEnd.getTime() - dStart.getTime();
        return (int) (diff / (24 * 3600 * 1000));
    }

    /**
     * 取得两个日期的小时之差
     * 
     * @param dStart
     * @param dEnd
     * @return
     */
    public static int getTimeSpanHour(Date dStart, Date dEnd) {
        long diff = dEnd.getTime() - dStart.getTime();
        return (int) (diff / (3600 * 1000));
    }

    /**
     * 解析年月�
     * 
     * @param obj
     * @return
     */
    public static Date parseAsDate(Object obj) {
        Date date = null;
        if (null != obj) {
            if (obj instanceof Date) {
                date = (Date) obj;
            } else if (obj instanceof String) {
                String ot = StringHelper.null2EmptyN(obj);
                if (ot.length() > 0) {
                    SimpleDateFormat formatter = new SimpleDateFormat(
                            DEFAULTDATEFORMAT);
                    try {
                        date = formatter.parse(ot);
                    } catch (ParseException e) {
                        logger.warn("parseAsDate exception:", e);
                    }
                }
            }
        }
        return date;
    }

    /**
     * 解析年月�
     * 
     * @param obj
     * @return
     */
    public static Calendar parseAsCalendar(Object obj) {
        Calendar calendar = null;
        if (null != obj) {
            if (obj instanceof Calendar) {
                calendar = (Calendar) obj;
            } else {
                String ot = StringHelper.null2EmptyN(obj);
                if (ot.length() > 0) {
                    DateFormat formatter = new SimpleDateFormat(
                            DEFAULTDATEFORMAT);
                    try {
                        calendar.setTime(formatter.parse(ot));
                    } catch (ParseException e) {
                        logger.warn("parseAsCalendar exception:", e);
                    }
                }
            }
        }
        return calendar;
    }

    /**
     * 解析年月日小时分
     * 
     * @param timeStr
     *            字符串格式必须为"yyyy-MM-dd HH:mm"或"yyyy-MM-dd HH:mm:ss"
     * @return
     * @throws ParseException
     */
    public static Calendar parseMidCalendar(String timeStr)
            throws ParseException {
        Calendar dd = null;
        if (null != timeStr) {
            try {
                dd = Calendar.getInstance();
                dd.setTime(dfMidDateTimeInstance.parse(timeStr));
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 取得两个日期的天数之差
     * 
     * @param dStart
     * @param dEnd
     * @return
     */
    public static int getCalendarTimeSpanDay(Calendar dStart, Calendar dEnd) {
        long diff = dEnd.getTimeInMillis() - dStart.getTimeInMillis();
        return (int) (diff / (24 * 3600 * 1000));
    }

    /**
     * 取得两个日期的小时间之差
     * 
     * @param dStart
     * @param dEnd
     * @return
     */
    public static int getCalendarTimeSpanHour(Calendar dStart, Calendar dEnd) {
        long diff = dEnd.getTimeInMillis() - dStart.getTimeInMillis();
        return (int) (diff / (3600 * 1000));
    }

    /**
     * 解析年月�
     * 
     * @param timeStr
     * @return
     * @throws ParseException
     */
    public static Calendar parseCalendarDate(String timeStr)
            throws ParseException {
        Calendar dd = null;
        if (null != timeStr) {
            try {
                dd = Calendar.getInstance();
                dd.setTime(dfDateInstance.parse(timeStr));
            } catch (ParseException e) {
                throw e;
            }
        }
        return dd;
    }

    /**
     * 取得两个日期的天数间�之差
     * 
     * @param dStart
     * @param dEnd
     * @return
     */
    public static int getTimestampTimeSpanDay(Timestamp dStart, Timestamp dEnd) {
        long diff = dEnd.getTime() - dStart.getTime();
        return (int) (diff / (24 * 3600 * 1000));
    }

    /**
     * 取得两个日期的小时间�之差
     * 
     * @param dStart
     * @param dEnd
     * @return
     */
    public static int getTimestampTimeSpanHour(Timestamp dStart, Timestamp dEnd) {
        long diff = dEnd.getTime() - dStart.getTime();
        return (int) (diff / (3600 * 1000));
    }

    /**
     * 自适应格式解析日期为Timestamp
     * 支持本类定义的常用格式
     * @param obj
     * @return
     */
    public static Timestamp parseStrAsTimestamp(String obj) {
        Timestamp date = null;
        if (null != obj) {
        	String ot = StringHelper.null2EmptyN(obj);
            if (ot.length() == DEFAULTDATEFORMAT.length()) {
            	  try {
                      date = new Timestamp(dfDateInstance.parse(ot)
                              .getTime());
                  } catch (ParseException e) {
                     logger.debug("parse", e);
                  }
            } else if (ot.length() == DEFAULTMIDDATEFORMAT.length()) {
            	  try {
                      date = new Timestamp(dfMidDateTimeInstance.parse(ot)
                              .getTime());
                  } catch (ParseException e) {
                	  logger.debug("parse", e);
                  }
            } else if (ot.length() == DEFAULTLONGDATEFORMAT.length()) {
                try {
                    date = new Timestamp(dfLongDateTimeInstance.parse(ot)
                            .getTime());
                } catch (ParseException e) {
                   logger.debug("parse", e);
                }
            } else if (ot.length() == DEFAULTMIDDATEFORMAT_H1.length()) {
	          	  try {
	                  date = new Timestamp(dfMidDateTimeH1Instance.parse(ot)
	                          .getTime());
	              } catch (ParseException e) {
	                 logger.debug("parse", e);
	              }
	        } else if (ot.length() == DEFAULTMIDDATEFORMAT_H2.length()) {
		      	  try {
		              date = new Timestamp(dfMidDateTimeH2Instance.parse(ot)
		                      .getTime());
		          } catch (ParseException e) {
		             logger.debug("parse", e);
		          }
		    }
        }
        return date;
    }
    
    
    /**
     * 解析时间戳
     * 
     * @param obj
     * @return
     */
    public static Timestamp parseAsTimestamp(Object obj) {
        Timestamp date = null;
        if (null != obj) {
            if (obj instanceof Timestamp) {
                date = (Timestamp) obj;
            } else if (obj instanceof java.sql.Date) {
                date = new Timestamp(((java.sql.Date) obj).getTime());
            } else if (obj instanceof java.util.Date) {
                date = new Timestamp(((java.util.Date) obj).getTime());
            } else if (obj instanceof Calendar) {
                date = new Timestamp(((Calendar) obj).getTimeInMillis());
            } else {
                // String ot = formatDate(StringHelper.null2EmptyN(obj));
                String ot = StringHelper.null2EmptyN(obj);
                date = parseStrAsTimestamp(ot);
            }
        }
        return date;
    }

	public static String formatLongDate(Object obj) {
		if(obj!=null){
			Timestamp ts = parseAsTimestamp(obj);
			if(ts!=null){
				return dfLongDateTimeInstance.format(ts);
			}
		}
		return null;
	}
	public static String formatMiddleDate(Object obj) {
		if(obj!=null){
			Timestamp ts = parseAsTimestamp(obj);
			if(ts!=null){
				return dfMidDateTimeInstance.format(ts);
			}
		}
		return null;
	}
}
